var express = require('express');
var crypto = require('crypto');
var router = express.Router();
var db=require('../db');
var User=require('../models/user');
var Post=require('../models/post');
const util = require('../util');

var moment = require('moment');
var auth = require('../auth');

/* GET home page. */
router.get('/', function(req, res, next) {

    console.log('index');

    res.render('index',{

    });

    //Post.find({},function(err,posts){
    //    if(err){
    //        req.session.message=err.message;
    //        return res.redirect('/');
    //    }
    //
    //    res.render('index',{
    //        posts:posts
    //    });
    //    //if(req.session.user){
    //    //
    //    //    console.log('login');
    //    //    res.render('home',{});
    //    //}else {
    //    //    res.render('index',{
    //    //        posts:posts
    //    //    });
    //    //
    //    //    console.log('not login');
    //    //}
    //
    //
    //
    //});

});

router.get('/home',function(req, res){
    res.render('home',{});
})

router.get('/tab',function(req, res){
    res.render('tab',{});
})


router.get('/modify_pwd',function(req, res){
    res.render('modify_pwd',{});
})

router.get('/yaoqing',function(req, res){
    res.render('yaoqing',{});
})

router.get('/personal',function(req, res){
    res.render('personal',{});
})

router.get('/findpwd',function(req, res){
    res.render('findpwd',{});
})

router.get('/ensurepwd',function(req, res){

    console.log('ensurepwd ' + req.param('type_id'));

    res.render('ensurepwd',{});
})



//发表微博
router.post('/post',function(req, res, next){
    var currentUser=req.session.user;
    var post=new Post({
        user:currentUser.name,
        post:req.body.article,
        updated:getTime(new Date())
    });
    post.save(function(err){
        if(err){
            req.session.message=err.message;
            return  res.redirect('/reg');
        }
        req.session.success="发表成功";
        res.redirect('/users/'+currentUser.name);
    });

});

function getTime(date){
   return date.getFullYear()+
    "-"+date.getMonth()+1+"-"+
    date.getDate()+" "+
    date.getHours()+":"+
    date.getMinutes();
}
router.get('/reg', isLogin);
//用户进入注册页面
router.get('/reg',function(req,res){
    res.render('reg',{title:"用户注册"});
});
router.post('/reg', isLogin);
//用户点击注册按钮
router.post('/reg',function(req,res){
   if(req.body['password']!= req.body['passwordconf']){
       req.session.error="两次密码不一致";
       return res.redirect('/reg');
   }
    var md5=crypto.createHash('md5');
    var password=md5.update(req.body.password).digest('base64');
    var newUser=new User({
        name:req.body['username'],
        password:password
    });
    User.findOne({name:newUser.name},function(err,user){
        if(user){
            err="用户名已经存在";
        }
        if(err){
           req.session.error=err;
           return  res.redirect('/reg');
        }
        newUser.save(function(err){
            if(err){
                req.session.error=err.message;
                return  res.redirect('/reg');
            }
            req.session.user=newUser;
            req.session.success="注册成功";
            res.redirect('/');
        });
    });
});

router.post('/modify_pwd',function(req, res){

    console.log('modify_pwd');

    if(req.body['password']!= req.body['repassword']){
        console.log('modify_pwd oo');
        req.session.error="两次新密码不一致";
        return  res.redirect('/modify_pwd');
    }
    //var md5=crypto.createHash('md5');
    var oldpassword=crypto.createHash('md5').update(req.body.oldpassword).digest('base64');
    var repassword=crypto.createHash('md5').update(req.body.repassword).digest('base64');
    var username = req.session.user.name;

    User.findOne({name:username,password:oldpassword},function(err,user){
        if(user){
            console.log(' 存在此用户');
            user.password = repassword;
            user.save(function(err){
                if(!err){
                    console.log('modify_pwd success');
                    req.session.user=user;
                    req.session.success="更新成功";
                    res.redirect('/');
                }else {
                    console.log('modify_pwd error');
                }

            });
        }else {
            console.log(' 没有此用户');
            req.session.error='没有此用户';
            res.redirect('/modify_pwd');
        }

    });

})



router.get('/login',isLogin);
router.get('/login',function(req,res){
    res.render('login',{title:"用户登陆"});
});
router.post('/login',isLogin);
router.post('/login',function(req,res){
    var md5=crypto.createHash('md5');
    var password=md5.update(req.body.password).digest('base64');
    User.findOne({name:req.body.username},function(err,user){
        if(!user){
            req.session.error="用户不存在";
            //return res.json({
            //    pass: false,
            //    data: "用户不存在"
            //})

            //return res.render('login',{
            //    pass: false,
            //    data: "用户不存在"
            //});
            return res.redirect('/login');
        }

        if(user.is_used == true){
            req.session.error="用户不能重复登录";
            return res.redirect('/login');
        }

        user.is_used = true;

        User.findOneAndUpdate({name:user.name}, user,function(err, doc){

            if (!err) {

                console.log(' acount update success');

            }else {
                console.log(' acount update falure:'+err);
            }

        });


        if(user.password!=password){
            req.session.error="密码错误";
            return res.json({
                pass: false,
                data: "密码错误"
            })
            //return  res.redirect('/login');
        }

        var tokendata = {
            id: user.id,
            name: user.name
        }
        var token = util.genToken(tokendata);

        //return res.json({
        //    pass: true,
        //    token: token,
        //    data: user
        //})



            req.session.name = user.name;
            req.session.pass = true;
            req.session.success="登录成功";
            console.log('session id:'+req.session.id);
            res.redirect('/');
    });
});
router.get('/logout',function(req,res){

    User.update({name:req.session.user.name},{$set:{is_used: false }}, function(err, user){

        if (!err){
            console.log('user udpate success '+ user.is_used ? "true":"false");

        }else {
            console.log('user udpate err '+ err);

        }
    });

    req.session.user=null;
    req.session.pass = false;
    res.redirect('/');
});
function isLogin(req,res,next){
    if(req.session.name && (req.session.pass == true)){
        req.session.message = "用户已登录";
        return res.redirect('/');
    }
    next();
}

module.exports = router;
